package longrise.phone.com.bjjt_henan.Utils;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import java.lang.ref.WeakReference;

/**
 * 获取验证码倒计时的帮助类
 */
public class CodeCountHelper {

    private TextView textView;

    private Handler handler;

    private int time = 60;

    public CodeCountHelper(TextView view) {
        this.textView = view;
        this.handler = new MyHandler(this);
    }

    private static class MyHandler extends Handler {

        private WeakReference<CodeCountHelper> reference;

        public MyHandler(CodeCountHelper helper) {
            this.reference = new WeakReference<CodeCountHelper>(helper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            CodeCountHelper helper = reference.get();
            if (null == helper) {
                return;
            }
            if (helper.time > 0) {
                helper.textView.setEnabled(false);
                helper.textView.setText("剩余" + helper.time-- + "秒");
                helper.handler.sendEmptyMessageDelayed(0, 1000);
            } else {
                helper.textView.setEnabled(true);
                helper.textView.setText("重发验证码");
                helper.time = 60;
            }
        }
    }

    public void startCount() {
        if (null != handler) {
            handler.sendEmptyMessage(0);
        }
    }

    public void destroy() {
        if (null != handler) {
            handler.removeMessages(0);
            handler = null;
        }
        textView = null;
    }
}
